#include "TransactionCommand.h"

#include "Common/Core.h"
#include "Protocol/ProtocolHelper.h"


using namespace Command;

TransactionCommand::TransactionCommand(MessageType requestType, MessageType responseType)
	: AbstractCommand(Protocol::Helper::commandNameByType(requestType))
	, _timeout(3000)
	, _isWaitingResponce(true)
	, _protocolRequestType(requestType)
	, _protocolResponseType(responseType)
{
}

MessageType TransactionCommand::protocolMessageType() const
{
	return _protocolRequestType;
}

void TransactionCommand::setResponseRecieved()
{
	_isWaitingResponce = false;
}

void TransactionCommand::sendData(const QByteArray& body)
{
	AbstractCommand::sendData(_protocolRequestType, body);
}

bool TransactionCommand::isResponseIncorrect(MessageType correctType, QDataStream& readStream)
{
	return hasWrongResponseType(correctType, readStream);
}

void TransactionCommand::processResponse(QByteArray& data)
{
	QDataStream readStream(&data, QIODevice::ReadOnly);

	if(isResponseIncorrect(_protocolResponseType, readStream))
		return;

	setResponseRecieved();
}

bool TransactionCommand::isWaitingForResponce()
{
	return _isWaitingResponce;
}

bool TransactionCommand::isTimedOut(quint32 msec)
{
	if(msec >= _timeout)
		return true;

	return false;
}

void TransactionCommand::sendData(quint8, const QByteArray&)
{
}

bool TransactionCommand::hasWrongResponseType(MessageType correctType, QDataStream& readStream)
{
	quint8 messageType;

	readStream >> messageType;

	if(correctType != messageType)
	{
		qDebug() << QString("%1:: Wrong response (%2)")
					.arg(Protocol::Helper::commandNameByType(correctType))
					.arg(Protocol::Helper::commandNameByType(messageType));
		return true;
	}

	return false;
}
